package cn.hou.socket01._01demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

//服务端接受 请求处理类
public class ServerHandler implements Runnable {
    private Socket socket;//接受服务端收到客户端请求时返回的socket

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;//输入流,接受数据
        PrintWriter out = null;//输出流,向客户端输出
        try {
            //InputStreamReader:字节流转向字符流的桥梁
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);//自动冲刷,否则不立即输出会
            String body = null;
            while (true) {
                body = in.readLine();
                if (body == null) break;
                //打印服务端接受到的数据
                System.out.println("服务端接受到的数据:" + body);
                out.println("服务端返回数据:{.....}");//给客户端返回数据
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            socket = null;
        }

    }


}
